<?php

class UsersController extends AdminController
{



	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	public function accessRules()
	{
		return array(
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('admin','update','view','UpdatePasswordAdmin'),
				'roles'=>array(Users::ROLE_MODER),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','view','create','update','UpdatePasswordAdmin'),
				'roles'=>array(Users::ROLE_ADMIN),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}


	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		if(!self::check_event_user($id)){
			throw new CHttpException(404,'У Вас недостатньо прав');
		}

		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Users('create');

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Users']))
		{
			$model->attributes=$_POST['Users'];

			if($model->isNewRecord){
				$model->salt=$model->get_salt();
				$model->password=$model->get_password_with_salt($model->password,$model->salt);
				$model->created=date('Y-m-d H:i:s');
				$model->last_visit=date('Y-m-d H:i:s');
			}

			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		if(!self::check_event_user($id)){
			throw new CHttpException(404,'У Вас недостатньо прав');
		}

		$model=$this->loadModel($id);

		if(isset($_POST['Users']))
		{
			if(!Yii::app()->user->checkAccess(Users::ROLE_ADMIN)){
				unset ($_POST['Users']['role']);
			}

			$model->attributes=$_POST['Users'];

			if($model->save()){
				$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax'])){
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
	}

	

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Users('search');
		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['Users'])){
			$model->attributes=$_GET['Users'];
		}

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionUpdatePasswordAdmin()
	{
		if(!Yii::app()->request->getQuery('id') && empty($_POST)){
			throw new CHttpException(404,'The requested page does not exist.');
		}

		if(!self::check_event_user(Yii::app()->request->getQuery('id'))){
			throw new CHttpException(404,'У Вас недостатньо прав');
		}
		
		$model=Users::model()->findByPk(Yii::app()->request->getQuery('id'));

		if(empty($model) && !isset($_POST['Users'])){
			throw new CHttpException(404,'The requested page does not exist.');
		}

		if(isset($_POST['Users']))
		{
			$model=Users::model()->findByPk($_POST['Users']['id']);
			$model->scenario='update_password_adminom';

			if(!empty($_POST['Users']['password'])){
				$model->password=$model->get_password_with_salt($_POST['Users']['password'],$model->salt);
				if($model->save()){
					$this->redirect(array('view','id'=>$model->id));
				}
			}else{
				$model->addError('password', 'Не введений пароль');
			}
				
		}

		$this->render('view',array(
			'model'=>$model,
		));
	}



		/**
	 * При виводы ынфо про одного юзера, перехыдна заміну пароля
	 *Створив для того, щоб не розмножувати код.
	 * @param <type> $id
	 * @return <type>
	 */
	public static function get_content_for_views_view($model){
		switch(Yii::app()->controller->action->id){
			case 'updatePasswordAdmin':
				$model->password='';
				return Yii::app()->controller->renderPartial('updatePassAdmin',array('model'=>$model),TRUE);
				break;

			default :
				return CHtml::link('Змінити пароль',  Yii::app()->controller->createUrl('/admin/users/updatePasswordAdmin',array('id'=>$model->id)));
		}
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Users the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Users::model()->findByPk($id);

		if($model===null){
			throw new CHttpException(404,'The requested page does not exist.');
		}

		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Users $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='users-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	/**
	 *перевірка чи може редагувати даного юзера
	 * метод створений для cgridview
	 * @param <type> $user_id
	 * @return <type>
	 */
	public static  function check_event_user($user_id){
		if(Yii::app()->user->checkAccess(Users::ROLE_ADMIN) || Yii::app()->user->id == $user_id){
			return TRUE;
		}else{
			return FALSE;
		}
	}

	/**
	 *перевірка чи може чи може бачити певні дані
	 * метод створений для cgridview
	 * @param <type> $user_id
	 * @return <type>
	 */
	public static  function check_view_text($user_id,$text){
		if(self::check_event_user($user_id)){
			return $text;
		}else{
			return ' ';
		}
	}

}
